<template>
  <div id="reportSearchList">
    <Breadcrumb content="报告查询" v-if="showBreadCrumbTag === true" />
    <GoBack :content="'报告查询'" v-if="showBreadCrumbTag === false" @closeDrawer="closeDrawer" :backUrl="url"></GoBack>
    <div class="bodyContent">
      <Splitpanes>
        <!-- 查询条件 -->
        <Pane size="17">
          <el-scrollbar style="height: 100%">
            <vxe-form ref="searchConForm" :data="form" title-width="90" class-name="padding-xs width-100-percentage">
              <vxe-form-item title="报告单元" class-name="width-100-percentage">
                <template #default>
                  <SelectWorkGroupAllDefaultAll ref="selectWorkGroupRef" :url="'/api/rptGroup/findPoctRptGroup'" :inputWidth="'100%'" @fatherMethod="searchWklt" :isShowAll="true" :isClear="true"></SelectWorkGroupAllDefaultAll>
                </template>
              </vxe-form-item>
              <vxe-form-item title="检验日期[起]" class-name="width-100-percentage">
                <template #default="{ data }">
                  <el-date-picker v-model="data.sampledaBegin" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="检验日期[起]" :shortcuts="shortcuts" style="width: 100%" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="检验日期[止]" class-name="width-100-percentage">
                <template #default="{ data }">
                  <el-date-picker v-model="data.sampledaEnd" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="检验日期[止]" :shortcuts="shortcuts" style="width: 100%" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="条码号范围" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-input v-enterNextInput class="enterNextInputFlag" type="text" v-model="data.reqNoS" placeholder="条码号[起]" clearable class-name="width-100-percentage" style="margin-bottom: 5px" @blur="handleSearch"></vxe-input>
                  <vxe-input v-enterNextInput class="enterNextInputFlag" type="text" v-model="data.reqNoE" placeholder="条码号[止]" clearable class-name="width-100-percentage" @blur="handleSearch"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="条码号" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-input v-enterNextInput class="enterNextInputFlag" type="text" v-model="data.reqNo" placeholder="条码号" clearable class-name="width-100-percentage" @blur="handleSearch"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="申请项目" class-name="width-100-percentage">
                <template #default="{ data }">
                  <VxePulldownMultiSelection ref="cleanFeeItemSelection" childIndex="fee" url="/lis/fee/item/findFeeItemList" @confirmClick="(data) => confirmList(data, 'fee')" :tableColumn="[
                    { field: 'feeCode', title: '编号' },
                    { field: 'feeName', title: '名称' }
                  ]" :displayTexts="['feeName']" :displayTextObj="data.feeName" :dicValues="data.fees" includeVal="id" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="病历号" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-input v-enterNextInput class="enterNextInputFlag" type="text" v-model="data.patNo" placeholder="病历号" clearable class-name="width-100-percentage" @blur="handleSearch"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="姓名" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-input v-enterNextInput class="enterNextInputFlag" type="text" v-model="data.patNa" placeholder="姓名" clearable class-name="width-100-percentage" @blur="handleSearch"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="性别" class-name="width-100-percentage">
                <template #default="{ data }">
                  <VxeDictSelection v-enterNextInput class="enterNextInputFlag" :url="'/api/sys/basDictDetail/findDictDetailList'" @confirmClick="dropSelectConfirm" :displayTexts="['name']" :displayTextObj="data.sex" :tableColumn="[{ field: 'code', title: '编码', width: `60px` }, { field: 'name', title: '名称', minWidth: `80px` }]" :aimKeys="[{ aimKey: 'sex', rowKey: 'code' }]" :dataObj="{ code: 'sex' }" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="病床" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-input v-enterNextInput class="enterNextInputFlag" type="text" v-model="data.bedNo" placeholder="病床" clearable class-name="width-100-percentage" @blur="handleSearch"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="采样时间" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-input v-enterNextInput class="enterNextInputFlag" v-model="data.samplingTime" type="date" placeholder="采样时间" transfer clearable :value-format="'yyyy-MM-dd'" :label-format="'yyyy-MM-dd'" class-name="width-100-percentage" @change="handleSearch" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="费别" class-name="width-100-percentage">
                <template #title>
                  <span class="padding-lr-xs">费别</span>
                </template>
                <template #default="data">
                  <VxeDictSelection v-enterNextInput :url="'/api/sys/basDictDetail/findDictDetailList'" @confirmClick="dropSelectConfirm" :displayTexts="['name']" :displayTextObj="form.feeType ? form.feeType : ''" :tableColumn="[{ field: 'code', title: '编码', width: `60px` }, { field: 'name', title: '名称', minWidth: `80px` }]" :aimKeys="[{ aimKey: 'feeType', rowKey: 'code' }]" :dataObj="{ code: 'CostType' }" @blur="handleSearch" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="是否审核" field="isChk" class-name="width-100-percentage" :item-render="{}">
                <template #default="{ data }">
                  <vxe-select v-model="data.isChk" placeholder="是否审核" clearable class-name="width-100-percentage">
                    <vxe-option v-for="(item, index) in chkStatusList" :key="index" :label="item.name" :value="item.code"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-form-item>
              <vxe-form-item title="是否打印" field="isPrint" class-name="width-100-percentage" :item-render="{}">
                <template #default="{ data }">
                  <vxe-select v-model="data.isPrint" placeholder="是否打印" clearable class-name="width-100-percentage">
                    <vxe-option v-for="(item, index) in [
                      {
                        value: 1,
                        label: '是'
                      },
                      {
                        value: 0,
                        label: '否'
                      }
                    ]" :key="index" :label="item.label" :value="item.value"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-form-item>
              <vxe-form-item title="科室" class-name="width-100-percentage">
                <VxePulldownSelection v-enterNextInput @blur="handleSearch" :url="'/api/sys/findDepartmentListbyCurrentUserOrg'" @confirmClick="dropPullDownConfirm" :tableColumn="[{ field: 'code', title: '编码', width: '60px' }, { field: 'name', title: '名称' }]" :aimKeys="[{ aimKey: 'reqDept', rowKey: 'code' }, { aimKey: 'reqDeptNa', rowKey: 'name' }]" :displayTexts="['name']" :displayTextObj="form.reqDept ? form.reqDept : ''" />
              </vxe-form-item>
              <vxe-form-item title="检验医师" class-name="width-100-percentage">
                <VxePulldownSelection v-enterNextInput :url="'/api/user/getUserInfoList'" @confirmClick="dropPullDownConfirm" :tableColumn="[{ field: 'username', title: '编号', width: '60px' }, { field: 'realname', title: '姓名' }]" :aimKeys="[{ aimKey: 'testDoctor', rowKey: 'username' }]" :displayTexts="['realname']" :displayTextObj="form.testDoctor ? form.testDoctor : ''" />
              </vxe-form-item>
              <vxe-form-item title="审核医师" class-name="width-100-percentage">
                <VxePulldownSelection v-enterNextInput :url="'/api/user/getUserInfoList'" @confirmClick="dropPullDownConfirm" :tableColumn="[{ field: 'username', title: '编号', width: '60px' }, { field: 'realname', title: '姓名' }]" :aimKeys="[{ aimKey: 'chkDoctor', rowKey: 'username' }]" :displayTexts="['realname']" :displayTextObj="form.chkDoctor ? form.chkDoctor : ''" />
              </vxe-form-item>
              <vxe-form-item title="病人类型" class-name="width-100-percentage">
                <template #default="{ data }">
                  <VxeDictSelection v-enterNextInput :url="'/api/sys/basDictDetail/findDictDetailList'" @confirmClick="dropSelectConfirm" :displayTexts="['name']" :displayTextObj="data.patType" :tableColumn="[{ field: 'code', title: '编码', width: `60px` }, { field: 'name', title: '名称', minWidth: `80px` }]" :aimKeys="[{ aimKey: 'patType', rowKey: 'code' }]" :dataObj="{ code: 'PATTYPE' }" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="样本类型" class-name="width-100-percentage">
                <VxePulldownSelection v-enterNextInput :url="'/api/lab/labSampleType/findSampleTypeList'" @confirmClick="dropPullDownConfirm" :tableColumn="[{ field: 'sampleTypeCode', title: '编号', width: '60px' }, { field: 'sampleTypeName', title: '名称' }]" :aimKeys="[{ aimKey: 'traits', rowKey: 'sampleTypeCode' }]" :displayTexts="['sampleTypeName']" :displayTextObj="form.traits ? form.traits : ''" />
              </vxe-form-item>

              <vxe-form-item title="检验目的" class-name="width-100-percentage">
                <template #default="data">
                  <VxePulldownSelection :url="'/api/bac/bacReqPurpose/findPurposeList'" @confirmClick="dropPullDownConfirm" :tableColumn="[{ field: 'purposeNo', title: '编码', width: '60px' }, { field: 'purposeName', title: '名称' }]" :aimKeys="[{ aimKey: 'testPurpose', rowKey: 'purposeNo' }]" :displayTexts="['purposeName']" :displayTextObj="form.testPurpose ? form.testPurpose : ''" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="耐药表型" class-name="width-100-percentage">
                <template #default="{ data }">
                  <VxePulldownMultiSelection ref="cleanFeeItemSelection" childIndex="fee" url="/lis/bac/base/resistant-phenotype/dict/findDictList" @confirmClick="(data) => resiPhenList(data, 'resiPhen')" :tableColumn="[
                    { field: 'code', title: '编号' },
                    { field: 'name', title: '名称' }
                  ]" :displayTexts="['name']" :displayTextObj="data.resiPhenName" :dicValues="data.resiPhens" includeVal="id" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="过滤无条码" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-checkbox v-model="data.isFilterNoSpecCode" @change="handleSearch"></vxe-checkbox>
                </template>
              </vxe-form-item>
              <vxe-form-item title-width="0" class-name="width-100-percentage">
                <template #title></template>
                <template #default>
                  <div class="width-100-percentage flex justify-center">
                    <vxe-button type="text" content="重置条件" class="button-blue" @click="resetForm"></vxe-button>
                    <vxe-button type="text" content="查询数据" class="button-blue" @click="handleSearch" icon="el-icon-search"></vxe-button>
                  </div>
                </template>
              </vxe-form-item>
            </vxe-form>
          </el-scrollbar>
        </Pane>
        <Pane size="83">
          <el-tabs v-model="activeName" type="card" @tab-click="getData">
            <el-tab-pane label="报告单" name="reportTab" style="height: 100%">
              <Splitpanes>
                <Pane size="60">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="预览" @click="previewRpt"></vxe-button>
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-print" content="打印" @click="previewPrint"></vxe-button>
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-feedback" content="电子病历" @click="getWlEhrName"></vxe-button>
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-file-excel" content="导出表格" @click="exportExcelReport('#printTest', '报告单')"></vxe-button>
                    </template>
                  </vxe-toolbar>
                  <vxe-table :loading="tableLoading" border align="left" show-overflow ref="wLTable" class="mytable-scrollbar" height="95%" :data="mainInfoList" :keyboard-config="{ isArrow: true }" :sort-config="{ trigger: 'cell' }" :row-config="{ isCurrent: true, isHover: true }" :cell-class-name="cellClassName" :column-config="{ resizable: true }" :scroll-y="{ enabled: true }" @current-change="handleRowClick">
                    <vxe-column type="checkbox" width="26"></vxe-column>
                    <vxe-column type="seq" title="#" width="30"></vxe-column>
                    <vxe-column field="isUrgent" width="16">
                      <template #header>
                        <span style="font-size: 7px; font-weight: 150">急</span>
                      </template>
                      <template #default="{ row }">
                        <i v-if="row.isUrgent === 1" class="el-icon-first-aid-kit">
                          <el-icon>
                            <WarnTriangleFilled />
                          </el-icon>
                        </i>
                      </template>
                    </vxe-column>
                    <vxe-column field="isPrint" width="16">
                      <template #header>
                        <span style="font-size: 7px; font-weight: 150">打</span>
                      </template>
                      <template #default="{ row }">
                        <i v-if="row.isPrint === 1" class="el-icon-printer">
                          <el-icon>
                            <Printer />
                          </el-icon>
                        </i>
                      </template>
                    </vxe-column>
                    <vxe-column field="isAutoPrint" width="16">
                      <template #header>
                        <span style="font-size: 7px; font-weight: 150">自</span>
                      </template>
                      <template #default="{ row }">
                        <i v-if="row.isAutoPrint === 1" class="el-icon-s-platform">
                          <el-icon>
                            <Monitor />
                          </el-icon>
                        </i>
                      </template>
                    </vxe-column>
                    <vxe-column field="isChk" width="16">
                      <template #header>
                        <span style="font-size: 7px; font-weight: 150">审</span>
                      </template>
                      <template #default="{ row }">
                        <i v-if="(row.isChk === 2) || (row.isChk === 1)" class="el-icon-finished">
                          <el-icon>
                            <SuccessFilled />
                          </el-icon>
                        </i>
                      </template>
                    </vxe-column>
                    <vxe-column field="isAlarm" width="16">
                      <template #header>
                        <span style="font-size: 7px; font-weight: 150">危</span>
                      </template>
                      <template #default="{ row }">
                        <i v-if="row.isAlarm === 1" class="el-icon-warning">
                          <el-icon>
                            <WarningFilled />
                          </el-icon>
                        </i>
                      </template>
                    </vxe-column>
                    <vxe-column field="rptGroupNa" title="报告单元" width="110" show-overflow></vxe-column>
                    <vxe-column field="sampleda" title="检验日期" width="70" show-overflow>
                      <template #default="{ row }">
                        <span>
                          {{
                            row.sampleda ? formatDateTime(new Date(row.sampleda), 'yyyy-MM-dd') : ''
                          }}
                        </span>
                      </template>
                    </vxe-column>
                    <vxe-column field="patNa" title="姓名" width="70" sortable>
                      <template #default="{ row }">
                        <span :style="{ color: row.displayColor }">{{ row.patNa }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="sex" title="性别" width="35" show-overflow>
                      <template #default="{ row }">{{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}</template>
                    </vxe-column>
                    <vxe-column field="age" title="年龄" width="50" show-overflow></vxe-column>
                    <vxe-column field="idNo" title="身份证号" width="130"></vxe-column>
                    <vxe-column field="telNo" title="联系电话" width="80"></vxe-column>
                    <vxe-column field="address" title="地址"></vxe-column>
                    <vxe-column field="bedNo" title="病床" width="50" show-overflow></vxe-column>
                    <vxe-column field="patNo" title="病历号" width="128">
                      <template #default="{ row }">
                        <span :style="{ color: row.displayColor }">{{ row.patNo }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="reqPurpose" title="申请目的" width="170" show-overflow></vxe-column>
                    <vxe-column field="sampleTypeNa" title="样本类型" min-width="100" show-overflow></vxe-column>
                    <vxe-column field="reqDeptNa" title="科室" width="70" show-overflow></vxe-column>
                    <vxe-column field="reqNo" title="条码号" width="90" sortable>
                      <template #default="{ row }">
                        <span :style="{ color: row.displayColor }">{{ row.reqNo }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="patType" title="病人类型" width="60">
                      <template #default="{ row }">
                        <span>{{ row.patTypeNa }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="sampleNo" title="标本号" width="57" sortable>
                      <template #default="{ row }">
                        <span :style="{ color: row.displayColor }">{{ row.sampleNo }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="testTime" title="上机时间" width="80" sortable>
                      <template #default="{ row }">
                        <span :style="{ color: row.displayColor }">
                          {{
                            row.testTime ? formatDateTime(new Date(row.testTime), 'yyyy-MM-dd') : ''
                          }}
                        </span>
                      </template>
                    </vxe-column>
                    <vxe-column field="printDoctorNa" title="打印人" width="60" show-overflow></vxe-column>
                    <vxe-column field="printTime" title="打印时间" width="80" sortable>
                      <template #default="{ row }">
                        <span :style="{ color: row.displayColor }">
                          {{
                            row.printTime ? formatDateTime(new Date(row.printTime), 'yyyy-MM-dd') : ''
                          }}
                        </span>
                      </template>
                    </vxe-column>
                    <vxe-column field="printCount" title="打印次数" width="60" show-overflow></vxe-column>
                  </vxe-table>
                </Pane>
                <Pane size="40">
                  <div style="height: 100%" v-if="resultType === 1">
                    <vxe-table ref="wLTableResult" :border="'inner'" :scroll-y="{ enabled: true ,gt: 100}" class="border-top solid mytable-scrollbar" v-loading="Resultloading" resizable show-overflow :mouse-config="{ selected: !currentWork.isFirstReviewed }" height="95%" :data="wLResults" :row-config="{ isArrow: true, isEnter: true, isCurrent: true }" :keyboard-config="{ isArrow: true }" :tooltip-config="{ showAll: true, enterable: true }" :cell-style="calcCellBgColor">
                      <vxe-column type="seq" width="24"></vxe-column>
                      <vxe-column field="itemNo" title="项目名称" width="160" show-overflow>
                        <template #default="{ row }">
                          <span>{{ row.itemNo + ' ' + row.itemNa }}</span>
                        </template>
                      </vxe-column>
                      <vxe-column field="testResult" title="检验结果" show-overflow></vxe-column>
                      <vxe-column field="resultFlag" title width="30">
                        <template #default="{ row }">
                          <span class="padding-lr-xs text-df">{{ getResultFlag(row.resultFlag) }}</span>
                          <span class="padding-lr-xs" v-if="row.isAlarm === '1' || row.isAlarm === 1">{{ row.alarmText }}</span>
                        </template>
                      </vxe-column>
                      <vxe-column field="ref" title="参考范围"></vxe-column>
                      <vxe-column field="resultDesc" title="结果说明"></vxe-column>
                      <vxe-column field="instrNa" title="仪器名称"></vxe-column>
                      <vxe-column field="rawData" title="仪器原始结果"></vxe-column>
                    </vxe-table>
                  </div>
                  <OrgResultComp ref="orgResultCompRef" :isChildren="true" v-if="resultType === 2" />
                </Pane>
              </Splitpanes>
            </el-tab-pane>
            <el-tab-pane label="申请单" name="specTab" style="height: 100%">
              <vxe-toolbar class-name="bg-gray">
                <template #buttons>
                  <!-- <vxe-button status="primary" class="margin-left-xs" content="导出表格" @click="exportExcel('#printTest', '表格')"></vxe-button> -->
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-file-excel" content="导出表格" @click="exportExcel('#printTest', '表格')"></vxe-button>
                </template>
              </vxe-toolbar>
              <vxe-table ref="printBarcodeTable" class="mytable-scrollbar" v-loading="loading" border height="95%" :cell-style="cellStyle" :cell-class-name="cellClassNameSpec" :data="printBarcodeList" @checkbox-change="checkboxStateChange" @cell-click="printBarcodeRowClick" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }" resizable show-overflow>
                <vxe-column type="checkbox" width="26"></vxe-column>
                <vxe-column type="seq" title="序号" width="30"></vxe-column>
                <vxe-column width="16" field="isUrgent" title="急诊" align="center">
                  <template #header>
                    <span style="font-size: 0.85rem; font-weight: 550">急</span>
                  </template>
                  <template #default="{ row }">
                    <span>{{ row.isUrgent ? '' : '' }}</span>
                  </template>
                </vxe-column>
                <vxe-column field="stateNa" title="标本状态" width="100"></vxe-column>
                <vxe-column field="patNa" title="姓名" width="80px"></vxe-column>
                <vxe-column field="sex" title="性别" width="40px">
                  <template #default="{ row }">{{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}</template>
                </vxe-column>
                <vxe-column field="age" title="年龄" width="60px"></vxe-column>
                <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
                <vxe-column field="bedNo" title="床号" width="80px"></vxe-column>
                <vxe-column field="reqPurpose" title="检验目的" width="280"></vxe-column>
                <vxe-column field="sampleType" title="样本类型" width="100"></vxe-column>
                <vxe-column field="reqDeptNa" title="科室" width="80px"></vxe-column>
                <vxe-column field="reqNo" title="条码号" width="140px"></vxe-column>
                <vxe-column field="reqDoctor" title="申请医生编号" width="120"></vxe-column>
                <vxe-column field="reqTime" title="申请时间" width="120"></vxe-column>
                <vxe-column field="samplingTime" title="采集时间" width="120"></vxe-column>
                <vxe-column field="signTime" title="签收时间" width="120"></vxe-column>
              </vxe-table>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
      <MultiRptPreview :reportList="reportList" :toggle="isPreviewRpt" :modalTitle="'报告预览'" />
      <!-- 静默打印 -->
      <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import GoBack from '@/components/GoBack.vue'; //返回组件
import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue';
import { IsEmpty, formatDateTime, sortByField } from '@/utils/common';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import VXETable from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import * as XLSX from 'xlsx';
import SelectWorkGroup from '../lab_sys/lab_bus/components/SelectWorkGroup.vue'; //报告单元引入下拉组件
import SelectWorkGroupAllDefaultAll from '../lab_sys/lab_bus/components/SelectWorkGroupAllDefaultAll.vue'; //报告单元默认全部引入下拉组件
import OrgResultComp from '../lab_sys/lab_bus/components/OrgResultComp.vue'; //
import SelectDataList from '@/components/SelectDataList.vue';
import MultiRptPreview from '@/components/MultiRptPreview.vue';
import { AppStore } from '@/stores/store';
import QuietPrint from '@/components/QuietPrint.vue';
import VxeDictSelection from '@/components/VxeDictSelection.vue';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import VxePulldownMultiSelection from '@/components/VxePulldownMultiSelection.vue';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';
import axios from 'axios';

let selectWorkGroupRef = ref(null);
let store = AppStore();
let { proxy }: any = getCurrentInstance();
let Floading = ref(false);
let Wloading = ref(false);
let tableLoading = ref(false);
let wLResults = reactive([]); //工作列表结果
let resultType = ref(1); //结果类型.1普通/2细菌
let activeName = ref('reportTab');
let loading = ref(false);
let Resultloading = ref(false);
const Axios = axios.create();
let wT = reactive({
  id: null,
  name: ''
});
let mainInfoList = reactive([]); //报告单元列表数据
let sexList: any = reactive([]); //字典表：性别
let chkStatusList: any = reactive([]); //字典表：审核状态
let patTypeList: any = reactive([]); //字典表：病人类型
const isPreviewRpt = ref(false);
const quietPrintRef = ref(null); //静默打印组件
const orgResultCompRef = ref(null); //细菌组件
let printParamsObj = ref(null);
let reportList = reactive([]);
const wLTable = ref(null); /**报告单表格对象 */
let deptOptions: any = reactive([]); //选择框
let cleanFeeItemSelection = ref(null);

let formData = reactive({});

const maininfoRef = ref(null);

const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    }
  }
];
//#region  自定义指令
// 自定义指令
const enterNextInput: ObjectDirective<HTMLElement> = {
  mounted(el) {
    el.addEventListener('keypress', (e) => {
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      if (charcode == 13) {
        const doms: any = document.getElementsByClassName('enterNextInputFlag');
        let list = [];
        for (let i = 0; i < doms.length; i++) {
          let node = doms[i].childNodes;
          if (node.length > 0) {
            node.forEach((v) => {
              if ((v.nodeName == 'TEXTAREA' || v.nodeName == 'INPUT') && !v.disabled) {
                list.push(v);
              }
            });
          }
        }
        for (let j = 0; j <= list.length; j++) {
          if (list[j] == document.activeElement) {
            if (j == list.length - 1) {
              return;
            }
            list[j + 1].focus();
            return;
          }
        }
      }
    });
  }
};

// 使用自定义指令
proxy.$.directives = { enterNextInput: enterNextInput };

let form = reactive({
  rptGroup: '',
  sampledaBegin: null,
  sampledaEnd: null,
  isChk: null,
  isPrint: null,
  isUrgent: null,
  reqNo: '',
  reqNoS: '', //申请号，也是标本号
  reqNoE: '',
  patNo: '', //病历号
  bedCode: '', // 床号
  organizationUnitCode: '', //医院条码
  name: '',
  patNa: '',
  reqDept: '', //科室//userInfo.employee.defaultAuthorizeDepId
  skipCount: 1,
  isFilterNoSpecCode: false,
  isQueryHistoryData: false,
  bedNo: '',
  samplingTime: null,
  feeType: '',
  testDoctor: '',
  chkDoctor: '',
  patType: '',
  traits: '',
  testPurpose: '',
  sex: '',
  fees: [],
  resiPhenName: '',
  resiPhens: [],
  feeIds: [],
  feeCodes: [],
  feeName: ''
});
let reportDay = ref(0);
let currentWork = reactive({}) as any;

defineExpose({ initPage, init });

let showBreadCrumbTag = ref(true); //当为true时显示的是普通面包屑 false显示的是返回组件
let url = ref(''); //抽屉要返回的路由地址

function init(row: any, row2: any) {
  url.value = row;
  showBreadCrumbTag.value = !row2;
}
// 关闭抽屉
function closeDrawer() {
  showBreadCrumbTag.value = true; //恢复成面包屑
  proxy.$emit('closeDrawer');
}

function getData(tab) {
  activeName.value = tab.paneName;
  if (tab.paneName == 'reportTab') {
    if (form.isQueryHistoryData) {
      getHistoyWklt();
    } else {
      getWklt();
    }
  } else {
    if (form.isQueryHistoryData) {
      findHistoyPrintBarcodeList();
    } else {
      findPrintBarcodeList();
    }
  }
}

// 页面加载时字典
onMounted(() => {
  reportDay.value = getOptionValueByCodeGlobalOption('bgcxmrrqfw') ? getOptionValueByCodeGlobalOption('bgcxmrrqfw') : 0;
  form.sampledaBegin = formatDateTime(new Date().valueOf() - reportDay.value * 24 * 60 * 60 * 1000, 'yyyy-MM-dd 00:00:00');
  form.sampledaEnd = formatDateTime(new Date().valueOf(), 'yyyy-MM-dd 23:59:59');

  getDictSexList(); //加载性别字典
  getDictChkStatusList(); //审核状态
  getDepyOptions(); //获取科室
  getDictPatTypeList(); //病人类型
});

function initPage(row: any) {
  form.patNa = row.patNa;
  form.patNo = row.patNo;
  form.sampledaBegin = formatDateTime(new Date().valueOf() - 180 * 24 * 60 * 60 * 1000, 'yyyy-MM-dd 00:00:00');
}
// 获取所有部门选项(下拉框)
function getDepyOptions() {
  const url = '/api/sys/findDepartmentList';
  proxy.$http
    .get(url, { params: { orgId: store.userInfo.orgId } })
    .then((res: any) => {
      deptOptions.push(...res.data.deptList);
    })
    .catch((err: any) => {
      VxeMessage('获取所有部门选项(下拉框)失败', VxeNotifyType.error);
    });
}

//获取性别数据字典
function getDictSexList() {
  sexList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'SEX' } })
    .then((res: any) => {
      sexList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

/**下拉选中 */
function dropSelectConfirm(e) {
  e.aimKeys.forEach((m) => {
    form[m.aimKey] = e.row[m.rowKey];
  });
  handleSearch();
}

/**下拉选中 */
function dropPullDownConfirm(e) {
  e.aimKeys.forEach((m) => {
    form[m.aimKey] = e.row[m.rowKey];
  });
  handleSearch();
}

//获取审核状态数据字典
function getDictChkStatusList() {
  chkStatusList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'chkStatus' } })
    .then((res: any) => {
      chkStatusList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//获取病人类型
function getDictPatTypeList() {
  patTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'PATTYPE' } })
    .then((res: any) => {
      patTypeList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 查询
function handleSearch() {
  if (activeName.value == 'reportTab') {
    if (form.isQueryHistoryData) {
      getHistoyWklt();
    } else {
      getWklt();
    }
  } else {
    if (form.isQueryHistoryData) {
      findHistoyPrintBarcodeList();
    } else {
      findPrintBarcodeList();
    }
  }
}

//获取工作列表
function searchWklt(selectedRadioId, selectedName) {
  form.rptGroup = selectedRadioId.value;
  if (activeName.value == 'reportTab') {
    if (form.isQueryHistoryData) {
      getHistoyWklt();
    } else {
      getWklt();
    }
  } else {
    if (form.isQueryHistoryData) {
      findHistoyPrintBarcodeList();
    } else {
      findPrintBarcodeList();
    }
  }
}

// 获取报告单列表
function getWklt() {
  mainInfoList.length = 0;
  wLResults.length = 0;
  VXETable.modal.message({
    id: 'myMsgLoading',
    content: '加载中,请稍后...',
    status: 'loading',
    duration: -1
  });
  Wloading.value = true;
  const url = '/lab/maininfo/findLabMaininfoPageList';
  let data: any = Object.assign({}, form);
  // data.sampledaBegin = formatDateTime(form.sampledaBegin, 'yyyy-MM-dd 00:00:00');
  // data.sampledaEnd = formatDateTime(form.sampledaEnd, 'yyyy-MM-dd 23:59:59');
  data.samplingTime = form.samplingTime ? formatDateTime(form.samplingTime, 'yyyy-MM-dd') : null;
  data.customSorting = '4';
  data.isFilterNoSpecCode = form.isFilterNoSpecCode;
  data.poct=1;
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      mainInfoList.length = 0;
      if (res.data.length > 0) {
        // mainInfoList.length = 0;
        proxy.$nextTick(() => {
          mainInfoList.push(...res.data);
          handleRowClick({ row: res.data[0] });
        });
      } else if (res.data.length == 0 && resultType.value === 2) {
        orgResultCompRef.value.clearData();
      }
      Wloading.value = false;
      VXETable.modal.close('myMsgLoading');
    })
    .catch((err) => {
      VXETable.modal.close('myMsgLoading');
      Wloading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 获取历史结果报告单列表
function getHistoyWklt() {
  mainInfoList.length = 0;
  wLResults.length = 0;
  VXETable.modal.message({
    id: 'myMsgLoading',
    content: '加载中,请稍后...',
    status: 'loading',
    duration: -1
  });
  Wloading.value = true;
  const url = '/lab/maininfo/findHisStoryLabMaininfoList';
  let data: any = Object.assign({}, form);
  data.samplingTime = form.samplingTime ? formatDateTime(form.samplingTime, 'yyyy-MM-dd') : null;
  data.customSorting = '4';
  data.isFilterNoSpecCode = form.isFilterNoSpecCode;
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      mainInfoList.length = 0;
      if (res.data.length > 0) {
        // mainInfoList.length = 0;
        proxy.$nextTick(() => {
          mainInfoList.push(...res.data);
          handleRowClick({ row: res.data[0] });
        });
      } else if (res.data.length == 0 && resultType.value === 2) {
        orgResultCompRef.value.clearData();
      }
      Wloading.value = false;
      VXETable.modal.close('myMsgLoading');
    })
    .catch((err) => {
      VXETable.modal.close('myMsgLoading');
      Wloading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

//rowClick
function handleRowClick({ row }) {
  wLResults.length = 0;
  resultType.value = 1;

  if (IsEmpty(row)) {
    wLResults = [];
    return;
  }
  if (row.businessType === '20') {
    //判断是细菌的报告单元
    resultType.value = 2;
    (proxy.$refs.wLTable as any).setCurrentRow(row);
    //进行组件查询
    proxy.$nextTick(() => {
      //进行组件查询
      orgResultCompRef.value.initPage(row); //调用菜单组件方法
    });
  } else {
    (proxy.$refs.wLTable as any).setCurrentRow(row);
    proxy.$emit('RowClick', row);
    Resultloading.value = true;
    const data = {
      rptGroup: row.rptGroup,
      sampleda: row.sampleda + ' 00:00:00',
      sampleNo: row.sampleNo
    };
    let url = '';
    if (form.isQueryHistoryData) {
      url = 'lab/maininfo/findHisStoryRptResultByLabMaininfo';
      proxy.$http
        .get(url, { params: data })
        .then((res: any) => {
          wLResults.length = 0;
          //wLResults.push(...res.data);
          wLResults.push(...sortByField(res.data, 'displayOrder', 'asc'));

          Resultloading.value = false;
        })
        .catch((err) => {
          Resultloading.value = false;
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      url = 'lab/maininfo/findRptResultByLabMaininfo?id=' + row.id;
      proxy.$http
        .get(url)
        .then((res: any) => {
          wLResults.length = 0;
          //wLResults.push(...res.data);
          wLResults.push(...sortByField(res.data, 'displayOrder', 'asc'));

          Resultloading.value = false;
        })
        .catch((err) => {
          Resultloading.value = false;
          VxeMessage(err, VxeNotifyType.error);
        });
    }
  }
  Object.assign(formData, row);
  Object.assign(currentWork, row);
}

//?单元格背景色
function cellClassName({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'isUrgent') {
    if (row.isUrgent === 1) {
      return 'bg-violet';
    } else {
      return '';
    }
  }
  if (column.property === 'isChk') {
    if (row.isChk === 2 || row.isChk === 1) {
      return 'bg-brilliantGreen';
    } else {
      return '';
    }
  }
  if (column.property === 'isAlarm') {
    if (row.isAlarm === 1) {
      return 'bg-brilliantRed';
    } else {
      return '';
    }
  }
  if (column.property === 'isAutoPrint') {
    if (row.isAutoPrint === 1) {
      return 'bg-darkBlue';
    } else {
      return '';
    }
  }
  if (column.property === 'isPrint') {
    if (row.isPrint === 1) {
      return 'bg-brilliantBlue';
    } else {
      return '';
    }
  }
}

//预览报告
let fullLoading = ref(false);
//#endregion

// 浏览
async function previewRpt() {
  const rowList = wLTable.value?.getCheckboxRecords(true);
  if (rowList.length === 0) {
    if (currentWork || IsEmpty(currentWork.id)) {
      VxeMessage('请选择一条数据', VxeNotifyType.warning);
      return;
    }
  }
  let isPreview = false;
  if (!rowList || rowList.length > 0) {
    rowList.forEach((item) => {
      if ((!item.isChk || item.isChk < 2) && item.businessType === '20') {
        isPreview = true;
      }
    });
  }
  if (isPreview) {
    VxeMessage('存在未审核,禁止预览', VxeNotifyType.warning);
    return;
  }

  isPreviewRpt.value = false;
  tableLoading.value = true;
  reportList.length = 0;
  if (IsEmpty(rowList)) {
    tableLoading.value = false;
    VxeMessage('预览失败', VxeNotifyType.error);
  }
  //染色节点走特有的处理
  /*await bacPreviewRpt(rowList);
  await bacJdPreviewRpt(rowList);*/

  proxy.$http
      .post('/lab/maininfo/viewRptBatch', rowList)
      .then((res: any) => {
        if (res.data && res.data.length > 0) {
          Object.assign(reportList, res.data);
          isPreviewRpt.value = true;
          tableLoading.value = false;
        }
      })
      .catch((err: any) => {
        tableLoading.value = false;
        VxeMessage('预览失败', VxeNotifyType.error);
      });
}
//微生物-染色结果打印的时候走特殊处理
async function bacPreviewRpt(arrSelects) {
  let dateData = [];
  arrSelects.forEach((item) => {
    if(item.bacFlowNode == 'STAINING'){
      dateData.push(item);
    }
  });
  if(dateData.length == 0){
    return;
  }
  //先根据路由的URL获取对应的报表信息
  let url = `/api/pubReport/getReportByBusFormCode?code=007`;
  proxy.$http
      .get(url)
      .then((res: any) => {
        const reportId = res.data.id;
        if (dateData.length > 0) {
          dateData.forEach((item) => {
            const data = {
              id: item.id,
              reportTemplateName: '染色报告.rdlx',
              reportId: reportId
            };
            reportList.push(data);
          });
        }
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

//微生物-鉴定结果
async function bacJdPreviewRpt(arrSelects) {
  let dateData = [];
  arrSelects.forEach((item) => {
    if(item.bacFlowNode == 'PEIYANG'){
      dateData.push(item);
    }
  });
  if(dateData.length == 0){
    return;
  }
  //先根据路由的URL获取对应的报表信息
  let url = `/api/pubReport/getPyReport`;
  proxy.$http
      .get(url, { params: { sampleda: dateData[0].sampleda,sampleNo: dateData[0].sampleNo,rptGroup: dateData[0].rptGroup } })
      .then((res: any) => {
        reportList.push(...res.data);

      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

//静默打印(普通检验)
async function previewPrint() {
  let data = [];
  const rowList = wLTable.value?.getCheckboxRecords(true);
  if (rowList.length === 0) {
    if (currentWork || IsEmpty(currentWork.id)) {
      VxeMessage('请选择一条数据', VxeNotifyType.warning);
      return;
    }
    if (!currentWork.isChk || currentWork.isChk < 2) {
      VxeMessage('存在未审核记录,不允许打印', VxeNotifyType.warning);
      return;
    }
    data.push(currentWork);
  } else {
    let isNoReviewed = false;
    rowList.forEach((item) => {
      data.push(item);
      if (!item.isChk || item.isChk < 2) {
        isNoReviewed = true;
      }
    });
    if (isNoReviewed) {
      VxeMessage('存在未审核记录,不允许打印', VxeNotifyType.warning);
      return;
    }
  }

  const reportRes: any = await new Promise((resolve, reject) => {
    const url = '/lab/maininfo/printRptBatch';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        let arr = [];
        res.data.forEach((e) => {
          arr.push({ ReportName: e.reportId, ReportParameters: [{ Name: 'Id', Value: e.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } });
        });
        printParamsObj.value = arr; //[{ ReportName: '1759924571139497986', ReportParameters: [{ Name: 'Id', Value: '123' }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };
      })
      .catch((err: any) => {
        VxeMessage('打印失败', VxeNotifyType.error);
      });
  });
  //printAction();
}

function getWlEhrName() {
  const url = '/api/sys/hisEmployee/getInterfaceData';
  const params = {
    url: (window as any).apiUrl.VUE_APP_INTERFACE_URL + '/EHR/getEHRByIdNo',
    code: 'GET_EHR'
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      if (!IsEmpty(JSON.parse(res.data).data)) {
        window.open(JSON.parse(res.data).data);
      }
    })
    .catch((err: any) => {
      VxeMessage('同步失败', VxeNotifyType.error);
    });
}

/**
 * 仅负责打印处理,不判断参数控制
 * @mainInfo 需要打印的上机记录
 */
function printAction() {
  const url = '/lab/maininfo/LabMainInfoPrint';
  proxy.$http
    .post(url, formData)
    .then((res: any) => {
      let arr = [];
      res.data.forEach((e) => {
        arr.push({ ReportName: e.reportId, ReportParameters: [{ Name: 'Id', Value: e.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } });
      });
      printParamsObj.value = arr; //[{ ReportName: '1759924571139497986', ReportParameters: [{ Name: 'Id', Value: '123' }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };
    })
    .catch((err: any) => {
      VxeMessage('打印失败', VxeNotifyType.error);
    });
}

function resetForm() {
  form.rptGroup = '';
  form.sampledaBegin = formatDateTime(new Date().valueOf() - reportDay.value * 24 * 60 * 60 * 1000, 'yyyy-MM-dd 00:00:00');
  form.sampledaEnd = formatDateTime(new Date().valueOf(), 'yyyy-MM-dd 23:59:59');
  form.isChk = null;
  form.isPrint = null;
  form.reqNo = '';
  form.reqNoS = ''; //申请号，也是标本号
  form.reqNoE = '';
  form.patNo = ''; //病历号
  form.bedNo = ''; // 床号
  form.organizationUnitCode = ''; //医院条码
  form.name = '';
  form.patNa = '';
  form.reqDept = '';
  form.skipCount = 1;
  form.feeType = '';
  form.samplingTime = null;
  form.feeType = '';
  form.testDoctor = '';
  form.chkDoctor = '';
  form.patType = '';
  form.traits = '';
  form.testPurpose = '';

  form.fees = [];
  form.feeIds = [];
  form.feeName = '';
  selectWorkGroupRef.value?.resetSelectedVal(); //重置选中的工作组
  cleanFeeItemSelection.value?.clearConfirmEvent({});
}

//Pulldown下拉选中事件【科室】
function pulldownSelectConfirm(e) {
  if (e.isChild) {
    //todo
  } else {
    e.aimKeys.forEach((item) => {
      form[item.targetField] = e.row[item.sourceField];
    });
  }
}

//点击每页数量
//单元格样式
function cellStyle({ row, rowIndex, column, columnIndex }) {
  if (row.isEnSameBg) {
    return { backgroundColor: row.sameSpecCodeBgColor };
  }
}

//单元格背景颜色
function cellClassNameSpec({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'isUrgent' && row.isUrgent === 1) {
    return 'bg-red';
  }
}

let printBarcodeList: any = reactive([]);

//打印选项选择改变
function checkboxStateChange({ checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) {
  if (row.isEnSameBg) {
    const arr = printBarcodeList.filter((e) => {
      return e.adviceGroupId === row.adviceGroupId && e.isEnSameBg;
    });
    if (arr && arr.length > 0) {
      const $xTable = proxy.$refs.printBarcodeTable as any;
      arr.forEach((e) => {
        $xTable.setCheckboxRow(e, checked);
      });
    }
  }
}

// 行点击事件
function printBarcodeRowClick({ row, rowIndex }) {
  //todo
}

//申请表列表
function findPrintBarcodeList() {
  printBarcodeList.length = 0;
  loading.value = true;
  let url = '/lab/reqMain/findLabReqMainPageList';
  let data: any = Object.assign({}, form);
  data.sampledaBegin = formatDateTime(form.sampledaBegin, 'yyyy-MM-dd 00:00:00');
  data.sampledaEnd = formatDateTime(form.sampledaEnd, 'yyyy-MM-dd 23:59:59');
  data.customSorting = '4';
  data.isFilterNoSpecCode = form.isFilterNoSpecCode;
  data.poct=1;
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      printBarcodeList.length = 0;
      printBarcodeList.push(...res.data);
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

//申请表列表(历史数据)
function findHistoyPrintBarcodeList() {
  printBarcodeList.length = 0;
  loading.value = true;
  let url = '/lab/reqMain/findHisStoryLabReqMainPageList';
  let data: any = Object.assign({}, form);
  data.sampledaBegin = formatDateTime(form.sampledaBegin, 'yyyy-MM-dd 00:00:00');
  data.sampledaEnd = formatDateTime(form.sampledaEnd, 'yyyy-MM-dd 23:59:59');
  data.customSorting = '4';
  data.isFilterNoSpecCode = form.isFilterNoSpecCode;
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      printBarcodeList.length = 0;
      printBarcodeList.push(...res.data);
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

//导出excel
function exportExcel(dom, title = '表格') {
  const $table = proxy.$refs.printBarcodeTable as any;
  const selectRows = $table.getCheckboxRecords();
  if (selectRows.length <= 0) {
    proxy.$XModal.message({ content: '还未选择需要导出的数据', status: 'warning' });
    return;
  }
  $table.exportData({ data: $table.getCheckboxRecords(), type: 'csv', filename: title, useStyle: true });
}

function exportExcelReport(dom, title = '报告单') {
  donloadReportExcel();
  // const $table = proxy.$refs.wLTable as any;
  // const selectRows = $table.getCheckboxRecords();
  // if (selectRows.length <= 0) {
  //   proxy.$XModal.message({ content: '还未选择需要导出的数据', status: 'warning' });
  //   return;
  // }
  // $table.exportData({ data: $table.getCheckboxRecords(), type: 'csv', filename: title, useStyle: true });
}

function donloadReportExcel() {
  const arr = mainInfoList.map((p) => p.id);
  if (!arr && arr.length <= 0) {
    VxeMessage('没有要导出的数据', VxeNotifyType.warning);
    return;
  }

  Axios({
    url: (window as any).apiUrl.VITE_SERVER_URL + '/lab/maininfo/downloadReportExcel',
    method: 'post',
    responseType: 'blob',
    data: { ids: arr }
  })
    // Axios({
    //   url: '/lab/maininfo/downloadReportExcel',
    //   method: 'get',
    //   responseType: 'blob'
    // })
    .then((res) => {
      const fileName = `报告查询-${formatDateTime(new Date(), 'yyyyMMddhhmmss')}`;
      const url = window.URL.createObjectURL(new Blob([res.data])); // { type: 'application/vnd.ms-excel' }
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', fileName + '.xls');
      document.body.appendChild(link);
      link.click();
      // 下载完成移除元素
      // document.body.removeChild(link)
      // 释放掉blob对象
      // window.URL.revokeObjectURL(url)
    })
    .catch((err) => {
      console.log(err);
    });
}

function exportDataToExcel(ArrayData) {
  try {
    const data = [];
    const first = [];
    const columns = (proxy.$refs.printBarcodeTable as any).getColumns();
    for (let index = 0; index < ArrayData.length; index++) {
      const element = ArrayData[index];
      const arr = [];
      for (let j = 1; j < columns.length; j++) {
        const e = columns[j];
        if (!IsEmpty(e.title)) {
          if (index === 0) {
            first.push(e.title);
          }
          if (typeof element[e.property] === 'boolean') {
            if (element[e.property] === true) {
              arr.push('是');
            } else {
              arr.push('否');
            }
          } else if (e.property && e.property.indexOf('.') > -1) {
            const a = e.property.split('.');
            if (element[a[0]] && element[a[0]][a[1]]) {
              arr.push(element[a[0]][a[1]]);
            } else {
              arr.push('');
            }
          } else {
            if (j === 1) {
              arr.push(index + 1);
            } else {
              if (e.title === '标本状态') {
                let a = '未采样';
                if (element.isSampled === true) {
                  a = '已采样';
                }
                if (element.isSigned === true) {
                  a = '已签收';
                }
                if (element.isApproved === true) {
                  a = '已审核';
                }
                if (element.isPrintRpt === true) {
                  a = '已打印报告';
                }
                arr.push(a);
              } else {
                arr.push(IsEmpty(element[e.property]) ? '' : element[e.property]);
              }
            }
          }
        }
      }
      if (index === 0) {
        data.push(first);
      }
      data.push(arr);
    }
    const ws = XLSX.utils.aoa_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, 'data.xlsx');
    (this as any).$XModal.close('exportMsg');
  } catch (error) {
    (this as any).$XModal.close('exportMsg');
  }
}

// #region 【电子病历】
// 按钮名称
let ehrButtonName = ref('电子病例');

// 点击组件表格行
function SelectRowClick(row) {
  form.traits = row.sampleTypeCode;
}
function getResultFlag(val) {
  const a = getOptionValueByCodeRptGroupOption('zjmaccsxs');
  if (a === '1' || a === 1) {
    if (val === 'H') {
      const b = getOptionValueByCodeRptGroupOption('pgjgbz');
      if (!IsEmpty(b)) {
        return b;
      }
      return '↑';
    }
    if (val === 'L') {
      const b = getOptionValueByCodeRptGroupOption('pdjgbz');
      if (!IsEmpty(b)) {
        return b;
      }
      return '↓';
    }
    if (val === 'P') {
      const b = getOptionValueByCodeRptGroupOption('yxjgbz');
      if (!IsEmpty(b)) {
        return b;
      }
      return '+';
    }
    if (val === 'Q') {
      const b = getOptionValueByCodeRptGroupOption('ryxjgbz');
      if (!IsEmpty(b)) {
        return b;
      }
      return '±';
    }
    if (val === 'M') {
      const b = getOptionValueByCodeRptGroupOption('zcjgbz');
      if (!IsEmpty(b)) {
        return b;
      }
      return '';
    }
    if (val === 'E') {
      const b = getOptionValueByCodeRptGroupOption('cwjgbz');
      if (!IsEmpty(b)) {
        return b;
      }
      return '×';
    }
    if (val === 'N') {
      const b = getOptionValueByCodeRptGroupOption('nxjgbz');
      if (!IsEmpty(b)) {
        return b;
      }
      return '√';
    }
  }
  if (val === 'H') {
    return '↑';
  }
  if (val === 'L') {
    return '↓';
  }
  if (val === 'P') {
    return '+';
  }
  if (val === 'Q') {
    return '±';
  }
  if (val === 'N') {
    return '√';
  }
  if (val === 'E') {
    return '×';
  }
  if (val === 'M') {
    return '';
  }
  return '';
}
/**
 * 单元格背景颜色
 *【1】是否启用系统选项颜色配置  encolorsetting
 *【2】偏高结果颜色  hresultcolor
 *【3】偏低结果颜色  lresultcolor
 *【4】阳性结果颜色  presultcolor
 *【5】正常结果颜色  mresultcolor
 *【6】弱阳性结果颜包  qresultcolor
 *【7】错误结果颜色  errresultcolor
 *【8】阴性结果颜色  nresultcolor
 *【9】结果标志颜色显示方式 jgbzysxsfs (0:背景色  1:文字颜色)
 */
function calcCellBgColor({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  /**偏高【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'H' && column && column.field === 'resultFlag') {
    //查询系统选项偏高显示颜色   背景色还是文字颜色
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('hresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#ff0000' };
  }
  /**偏高【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'H' && column && column.field === 'testResult') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('hresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#ff0000', color: '#fff' };
  }

  /**偏低【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'L' && column && column.field === 'resultFlag') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('lresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#0035ff' };
  }
  /**偏低【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'L' && column && column.field === 'testResult') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('lresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ff', color: '#fff' };
  }

  /**阳性【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'P' && column && column.field === 'resultFlag') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('presultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#0035ff' };
  }
  /**阳性【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'P' && column && column.field === 'testResult') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('presultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ff', color: '#fff' };
  }

  /**弱阳性【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'Q' && column && column.field === 'resultFlag') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('qresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#0035ee' };
  }
  /**弱阳性【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'Q' && column && column.field === 'testResult') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('qresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ee', color: '#fff' };
  }

  /**错误【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'E' && column && column.field === 'resultFlag') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('errresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#800000' };
  }
  /**错误【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'E' && column && column.field === 'testResult') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('errresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#800000', color: '#fff' };
  }

  /**正常【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'M' && column && column.field === 'resultFlag') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('mresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#000' };
  }
  /**正常【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'M' && column && column.field === 'testResult') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('mresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { color: '#000' };
  }

  /**阴性【标志】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'N' && column && column.field === 'resultFlag') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const b = getOptionValueByCodeRptGroupOption('jgbzysxsfs');
      const c = getOptionValueByCodeGlobalOption('nresultcolor');
      if (b === '0' || b === 0) {
        if (!IsEmpty(c)) {
          return { background: c, color: '#fff' };
        }
      }
      if (b === '1' || b === 1) {
        if (!IsEmpty(c)) {
          return { color: c };
        }
      }
    }
    return { color: '#000' };
  }
  /**阴性【结果】 */
  if (row && row.resultFlag && !IsEmpty(row.resultFlag) && row.resultFlag === 'N' && column && column.field === 'testResult') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('nresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { color: '#000' };
  }

  /**危急值 颜色 */
  if (row && !IsEmpty(row.isAlarm) && row.isAlarm === 1 && column && column.field === 'itemNo') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    const b = getOptionValueByCodeGlobalOption('isalarmcolor');
    const d = getOptionValueByCodeGlobalOption('wjzyssfxswbjys'); /**危急值颜色显示是否为背景颜色 wjzyssfxswbjys */
    if (a === 1 || a === '1') {
      if (!IsEmpty(b)) {
        if (d && (d === '1' || d === 1)) {
          return { background: b, color: '#fff' };
        } else {
          return { color: b };
        }
      }
    }
  }
}

function confirmList(data, keyName) {
  form[keyName + 's'] = [];
  form[keyName + 'Ids'] = [];
  form[keyName + 'Codes'] = [];
  form[keyName + 'Name'] = '';
  if (IsEmpty(data.aimKeys) || data.aimKeys.length === 0) {
    const arr = data.arr;
    form[keyName + 's'] = arr;
    if (arr.length !== 0) {
      arr.forEach((item) => {
        if (item.id) {
          form[keyName + 'Ids'].push(item.id);
          form[keyName + 'Codes'].push(item.feeCode);
        } else {
          form[keyName + 'Ids'].push(item.feeCode);
        }
        if (item.name) {
          form[keyName + 'Name'] += item.name + ',';
        } else if (item[keyName + 'Name']) {
          form[keyName + 'Name'] += item[keyName + 'Name'] + ',';
        } else {
          form[keyName + 'Name'] += item.realname + ',';
        }
      });

      if (form[keyName + 'Name'] && form[keyName + 'Name'].trim()) {
        form[keyName + 'Name'] = form[keyName + 'Name'].slice(0, -1);
      }
    }
  } else {
    data.arr.forEach((item) => {
      data.aimKeys.forEach((val) => {
        form[val.targetField + 's'].push(item);
        form[val.targetField + 'Ids'].push(item[val.targetField + 'Id']);
        form[val.targetField + 'Name'] += item[val.targetField].name + ',';
      });
    });
  }
}
function resiPhenList(data, keyName) {
  form[keyName + 's'] = [];
  form[keyName + 'Ids'] = [];
  form[keyName + 'Codes'] = [];
  form[keyName + 'Name'] = '';
  if (IsEmpty(data.aimKeys) || data.aimKeys.length === 0) {
    const arr = data.arr;
    form[keyName + 's'] = arr;
    if (arr.length !== 0) {
      arr.forEach((item) => {
        if (item.id) {
          form[keyName + 'Ids'].push(item.id);
          form[keyName + 'Codes'].push(item.code);
        } else {
          form[keyName + 'Ids'].push(item.code);
        }
        if (item.name) {
          form[keyName + 'Name'] += item.name + ',';
        } else if (item[keyName + 'Name']) {
          form[keyName + 'Name'] += item[keyName + 'Name'] + ',';
        } else {
          form[keyName + 'Name'] += item.realname + ',';
        }
      });

      if (form[keyName + 'Name'] && form[keyName + 'Name'].trim()) {
        form[keyName + 'Name'] = form[keyName + 'Name'].slice(0, -1);
      }
    }
  } else {
    data.arr.forEach((item) => {
      data.aimKeys.forEach((val) => {
        form[val.targetField + 's'].push(item);
        form[val.targetField + 'Ids'].push(item[val.targetField + 'Id']);
        form[val.targetField + 'Name'] += item[val.targetField].name + ',';
      });
    });
  }
}

//发送本地服务 打开电子病历
// function requestLocalService(data) {
//   OpenEhrAction(data);
//   (this as any).$XModal.message({content: '正在打开电子病历...', status: 'success'});
// }

// #endregion
</script>
<style lang="scss" scoped>
#reportSearchList {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    :deep(.el-tabs__header) {
      margin: 0 !important;
    }

    :deep(.el-tabs) {
      height: 100%;

      .el-tabs__content {
        height: calc(100% - 41px);
      }
    }
  }

  .splitpanes {
    background-color: $base-white;
    height: 100%;
  }

  :deep(.splitpanes__pane) {
    overflow: visible;
  }

  :deep(.el-table) {
    th,
    .cell {
      padding: 2px 0;
      font-size: 14px;
    }

    td {
      padding: 0;
    }

    .cell.el-tooltip {
      min-width: 0;
      padding: 0 2px;

      // 急诊
      .el-icon-first-aid-kit {
        color: $danger-color;
      }

      // 打印
      .el-icon-printer {
        color: $warning-color;
      }

      // 审核
      .el-icon-coordinate {
        color: $brand-color;
      }

      // 完成
      .el-icon-circle-check {
        color: $success-color;
      }

      // 危急
      .el-icon-warning {
        color: $danger-color;
      }
    }

    .table-icon .cell.el-tooltip {
      padding: 0;

      i {
        font-size: 12px;
        font-weight: 700;
      }
    }

    .ultra-small-font {
      font-weight: 500;
      font-size: 12px;
      line-height: 12px;
      transform: scale(0.9);
    }
  }

  :deep(.vxe-cell) {
    padding-left: 5px;
  }

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 0 5px 0 0;
  }
}
</style>
